// 只有这些充值方式
export const bankPayMethods = [1, 2, 3, 4, 5, 6]
// 充值方式对应的名称
export const bankPayType = [
  { paymenttype: 1, payname: 'bankcard' },
  { paymenttype: 2, payname: 'momo' },
  { paymenttype: 3, payname: 'zalo' },
  { paymenttype: 4, payname: 'viettel' },
  { paymenttype: 5, payname: 'scratchcard' },
  { paymenttype: 6, payname: 'usdt' },
]
export const netWorkArr = [
  { text: 'TRC20', value: 1 },
  { text: 'ERC20', value: 2 },
]

/**
 * @description 转换用户名
 */
export const userNameHiding = (name: string, num = 2) => {
  if (name) {
    const hiddenChars1 = '**'
    let visibleChars
    visibleChars = name.slice(0, num) + hiddenChars1 + name.slice(-2)
    return visibleChars
  } else {
    return ''
  }
}

export const sleep = (time: number) => {
  return new Promise((resolve) => setTimeout(resolve, time))
}

/**
 * 打开外部链接
 * @param val 当前点击项菜单
 */
export const handleOpenLink = (url: string) => {
  let dom = document.createElement('a')
  dom.setAttribute('href', `${url}`)
  dom.setAttribute('target', '_blank')
  document.body.appendChild(dom)
  dom.click()
  document.body.removeChild(dom)
}

/**
 * 获取客服链接
 * @param serviceList 客服配置数组
 */
export const getCustomerServiceLink = (serviceList: any) => {
  let telegramUrl = null
  for (let i = 0; i < serviceList.length; i++) {
    if (serviceList[i].name_key === "telegram") {
      telegramUrl = serviceList[i].url;
      break;
    }
  }
  let default_tg = "https://t.me/PKBET888"
  return telegramUrl || default_tg
}

/**
 * 小数或整数(不可以负数)
 * @param val 当前值字符串
 * @returns 返回处理后的字符串
 */
export function verifyNumberIntegerAndFloat(val: string) {
  // 匹配空格
  let v = val.replace(/(^\s*)|(\s*$)/g, '')
  // 只能是数字和小数点，不能是其他输入
  v = v.replace(/[^\d.]/g, '')
  // 以0开始只能输入一个
  v = v.replace(/^0{2}$/g, '0')
  // 保证第一位只能是数字，不能是点
  v = v.replace(/^\./g, '')
  // 小数只能出现1位
  v = v.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
  // 小数点后面保留2位
  v = v.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
  // 返回结果
  return v
}

/**
 * 金额用 `,` 区分开
 * @param val 当前值字符串
 * @returns 返回处理后的字符串
 * isDecimal 是否需要舍弃小数，不需要舍弃 true, 需要舍弃 false
 */
export function verifyNumberComma(val: string, isDecimal: boolean = true) {
  // 调用小数或整数(不可以负数)方法
  let v: any = verifyNumberIntegerAndFloat(val)
  v = isDecimal ? v : Math.trunc(v) // 直接舍弃小数

  // 字符串转成数组
  v = v.toString().split('.')
  // \B 匹配非单词边界，两边都是单词字符或者两边都是非单词字符
  v[0] = v[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  // 数组转字符串
  v = v.join('.')
  // 返回结果
  return v
}
// 对象转时间显示 dd/MM/yyyy HH:mm:ss
export function convertObjectToDateString(obj: any, origin?: boolean): string {
  let rs = `${padZero(obj.day)}/${padZero(obj.month)}/${obj.year} ${padZero(
    obj.hour
  )}:${padZero(obj.minute)}:${padZero(obj.second)}`
  if (origin) {
    rs = `${obj.year}-${padZero(obj.month)}-${padZero(obj.day)} ${padZero(
      obj.hour
    )}:${padZero(obj.minute)}:${padZero(obj.second)}`
  }
  return rs == '00/00/00 00:00:00' ? '--' : rs
}
function padZero(n: number): string {
  if (n > 9) return n.toString()
  return '0' + n
}

/**
 * @description 复制
 * @param text
 * @returns
 */
export function copyFn(text: string) {
  // 使用 Clipboard API
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(text).then(function () {
      console.log('复制成功: ' + text);
    }).catch(function (err) {
      console.error('复制失败: ', err);
    });
  } else {
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.style.cssText = `
      position: fixed;
      top: -9999px;
      left: -9999px;
      opacity: 0;
      user-select: none;
      -webkit-user-select: none;
      pointer-events: none;
    `;
    document.body.appendChild(textarea);

    // 临时设置只读属性
    textarea.setAttribute('readonly', 'true');
    textarea.select();

    // 延迟恢复并移除元素
    setTimeout(() => {
      textarea.removeAttribute('readonly');
      document.body.removeChild(textarea);
      textarea.blur();  // 强制移除焦点
    }, 300);
  }
}
/**
 *  精确小数点，截取位数，不四舍五入
 *  l 小数点位数
 *  精度丢失问题
 * */
export const toFixedNumber = (value: any, l = 2) => {
  if (!value) {
    return `0.${''.padEnd(l, '0')}`
  }
  const str = value.toString().split('.')
  const str1 = str[1] ? str[1].substr(0, l).padEnd(l, '0') : ''.padEnd(l, '0')
  return str[0] + '.' + str1
}

/**
 * 将数字或字符串转换为以 "k" 为单位的格式
 * @param {number | string} input - 需要转换的数字或字符串
 * @returns {string} - 转换后的字符串，带有 "k" 单位
 */
export function formatNumber(input: number | string): string {
  // 将输入转换为浮点数
  let number = parseFloat(input.toString())

  // 如果输入不是有效数字，返回原输入
  if (isNaN(number)) {
    return input.toString()
  }

  // 如果数字小于 1000，直接返回该数字
  if (number < 1000) {
    return number.toString()
  }

  // 将数字转换为以 "k" 为单位的格式，并保留两位小数
  let formattedNumber = (number / 1000).toFixed(2) + 'k'
  return formattedNumber
}
/**
 * 将数字或字符串转换为以 "k" W 为单位的格式
 * @param {number | string} input - 需要转换的数字或字符串
 * @returns {string} - 转换后的字符串，带有 "k" 单位
 */
export function formatBigNumber(input: number | string) {
  if (!input) return input
  // 将输入转换为浮点数
  let number = parseFloat(input.toString())

  // 如果输入不是有效数字，返回原输入
  if (isNaN(number)) {
    return input.toString()
  }

  // 如果数字小于 10000，直接返回该数字
  if (number < 10000) {
    return number.toString()
  }
  if (number >= 10000 && number < 10000000) {
    return (number / 10000).toFixed(1) + 'W'
  }
  if (number >= 10000000) {
    return (number / 10000000).toFixed(1) + 'KW'
  }
}

export function formatBigNumberK(input: number | string) {
  // 将输入转换为浮点数
  let number = parseFloat(input.toString())

  // 如果输入不是有效数字，返回原输入
  if (isNaN(number)) {
    return input.toString()
  }

  // 如果数字小于 10000，直接返回该数字
  if (number < 1000) {
    return number.toString()
  }
  if (number >= 1000 && number < 1000000) {
    return (number / 1000).toFixed(2) + 'K'
  } else if (number >= 1000000) {
    return (number / 1000000).toFixed(2) + 'M'
  }
}

/**
 * 将对象数组 按字母顺序排序
 * @param arr 对象数组；prop：要排序的对象属性key名
 * @returns: nut-elevator list格式
 */
export function sortAndGroupByLetter(arr: any, prop: string) {
  // 按prop属性排序
  const sorted = arr?.sort((a: any, b: any) =>
    a[prop]?.localeCompare(b[prop], 'en')
  )
  // 根据首字母分组
  const grouped = sorted.reduce((grouped: any, item: any) => {
    const firstChar = (item[prop] && item[prop][0]?.toUpperCase()) || '*'
    grouped[firstChar] = grouped[firstChar] || []
    grouped[firstChar].push(item)
    return grouped
  }, {})
  let list: any = []
  Object.keys(grouped).forEach((key) => {
    let item = { title: key, list: <any>[] }
    console.log(key, grouped[key])
    grouped[key].map((it: any) => {
      item.list.push(it)
    })
    list.push(item)
  })

  // 获取分组的字母数组
  const letters = Object.keys(grouped).sort()

  // 返回分组后的对象，包含字母数组和对应的分组数组
  return { list, letters, grouped }
}
// 去除千位符
export const removeComma = (val: any) => {
  return val ? Number(val.replaceAll(',', '')) : 0
}
export const handleFocus = () => {
  const bodyElement: any = document.querySelector('body')
  const htmlElement: any = document.querySelector('html')
  bodyElement.style.height = '100%'
  bodyElement.style.overflowY = 'hidden'
  htmlElement.style.height = '100%'
  htmlElement.style.overflowY = 'hidden'
}
export const handleBlur = () => {
  const bodyElement: any = document.querySelector('body')
  const htmlElement: any = document.querySelector('html')
  bodyElement.style.cssText = ''
  htmlElement.style.cssText = ''
}
export const getBlientType = () => {
  // export enum ClientType {
  //     PCWeb = 1,
  //     MobileWeb,
  //     Android,
  //     IOS
  // }
  // 后期判断使用
}
// 用于游戏数据分割成有分页的效果
export const splitArrayIntoChunks = (array: any, chunkSize: number) => {
  let result = []
  for (let i = 0; i < array.length; i += chunkSize) {
    result.push(array.slice(i, i + chunkSize))
  }
  return result
}
// 银行卡，显示前4位和后4位, 银行卡最少6位
export const maskTxtString = (str: any, firstNum: number = 4) => {
  if (str?.length <= 8) {
    return str?.substr(0, 4) + ' **** **** '
  }
  return str?.substr(0, firstNum) + ' **** **** ' + str?.substr(-4)
}
// usdt 地址
export const validateCryptoAddress = (address: any, type: any) => {
  // const regex_1 = /^(1|3|bc1)[a-zA-Z0-9]{25,39}$/; // BTC
  const regex_2 = /^0x[a-fA-F0-9]{40}$/ // ETH, ERC20
  // const regex_3 = /^(L|M|3)[a-zA-Z0-9]{25,33}$/; // LTC
  // const regex_4 = /^r[a-zA-Z0-9]{24,34}$/; // XRP
  // const regex_5 = /^(D|9)[a-zA-Z0-9]{33}$/; // DOGE
  const regex_6 = /^T[a-zA-Z0-9]{33}$/ // TRC20
  const check: any = {
    1: regex_6,
    2: regex_2,
  }
  return check[type].test(address)
}

export const getDeviceType = () => {
  const userAgent = navigator.userAgent || navigator.vendor

  if (
    userAgent.match(/iPad/i) ||
    userAgent.match(/iPhone/i) ||
    userAgent.match(/iPod/i)
  ) {
    return 'iOS' // iOS device
  } else if (userAgent.match(/Android/i)) {
    return 'Android' // Android device
  } else {
    return 'unknown' // 其他设备
  }
}
// 设备环境判断 isIosWKWebView isAndroidApp
export const isIosWKWebView = () => {
  const userAgent = navigator.userAgent.toLowerCase()
  const isIOS = /iphone|ipad|ipod/.test(userAgent)
  const isWKWebView =
    (window as any).webkit && (window as any).webkit.messageHandlers
  const isNotInBrowser = !/safari|chrome|crios|fxios|edgios|firefox|opera/.test(
    userAgent
  )
  return isIOS && isWKWebView && isNotInBrowser
}
export const isAndroidApp = () => {
  return !!(window as any).AndroidInterface
}
export const isAppleDevice = () => {
  var userAgent = navigator.userAgent
  // 检查是否包含 iPhone、iPad 或 iPod
  return /iPhone|iPad|iPod/.test(userAgent)
}
//获取一个格式化的时间
export const getDateFromat = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  const datatime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  return datatime
}
export const throttleAction = (func: any, limit: any) => {
  let lastFunc: any
  let lastRan: any
  return function (this: any, ...args: any) {
    const context = this
    if (!lastRan) {
      func.apply(context, args)
      lastRan = Date.now()
    } else {
      clearTimeout(lastFunc)
      lastFunc = setTimeout(function () {
        if (Date.now() - lastRan >= limit) {
          func.apply(context, args)
          lastRan = Date.now()
        }
      }, limit - (Date.now() - lastRan))
    }
  }
}
// 添加前导零
export const addLeadingZero = (num: string | number) => {
  return Number(num) < 10 ? '0' + num : num.toString();
}

// 货币格式化
export const currencyMoney = (money: number, decimal: number = 2, needIcon: boolean = false) => {
  let coinIcon = '';
  if (needIcon) {
    // TODO 暂时写死₫
    coinIcon = '₫';
  }
  if (isNaN(money)) {
    money = 0
  }
  money = Number(money);
  // 使用 toLocaleString 格式化货币
  const options: Intl.NumberFormatOptions = {
    minimumFractionDigits: decimal,
    maximumFractionDigits: decimal,
  };
  const formattedMoney = money.toLocaleString('en-US', options);

  return `${coinIcon}${formattedMoney}`;
}
export const deepClone = (obj: any): any => {
  if (obj === null || typeof obj !== 'object') {
    return obj // 如果是基础类型或 null，直接返回
  }
  if (obj instanceof Date) {
    return new Date(obj) // 处理 Date 类型
  }
  if (obj instanceof Array) {
    return obj.map((item) => deepClone(item)) // 处理数组，递归拷贝每一项
  }
  const clonedObj: any = {}
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      clonedObj[key] = deepClone(obj[key]) // 递归处理每个属性
    }
  }
  return clonedObj // 返回拷贝后的对象
}

export function formatTime(timestamp: any) {
  // 时间戳为10位需*1000，时间戳为13位不需乘1000
  var date = new Date(timestamp * 1000)
  var Y = date.getFullYear() + '  '
  var M =
    (date.getMonth() + 1 < 10
      ? '0' + (date.getMonth() + 1)
      : date.getMonth() + 1) + '/'
  var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '/'
  var h = date.getHours() + ':'
  var m = date.getMinutes() + ':'
  var s = date.getSeconds()
  return D + M + Y + h + m + s
}
export function joinURL(baseURL: any, path: any) {
  if (!path) return ''
  if (!baseURL) baseURL = ''
  // 时间戳为10位需*1000，时间戳为13位不需乘1000
  if (baseURL.endsWith('/')) {
    baseURL = baseURL.slice(0, -1);
  }
  // 移除 path 开头的斜杠（如果有）
  if (path?.startsWith('/')) {
    path = path.slice(1);
  }
  // 拼接 URL
  return baseURL + '/' + path;
}


// 开启页面下拉刷新
export const enablePullToRefresh = () => {
  document.documentElement.style.overscrollBehavior = "auto"; // 设置 html
  document.body.style.overscrollBehavior = "auto"; // 设置 body
}

// 关闭页面下拉刷新
export const disablePullToRefresh = () => {
  document.documentElement.style.overscrollBehavior = "none"; // 设置 html
  document.body.style.overscrollBehavior = "none"; // 设置 body
}